﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Configuration;

namespace Otgruzka.Controls
{
    public partial class Paging : System.Web.UI.UserControl
    {
        protected System.Drawing.Color ActivePageColor = System.Drawing.Color.FromName("#6b8cbe");
        protected int CountVisible
        {
            get
            {
                int countVisible = (ConfigurationManager.AppSettings["CountVisiblePageNums"] != null) ? Convert.ToInt32(ConfigurationManager.AppSettings["CountVisiblePageNums"]) : 4;
                return countVisible;
            }
        }
        public int? CountRows { get; set; }
        public int CountPages
        {
            get
            {
                int onPage = (ConfigurationManager.AppSettings["RowsOnPage"] != null) ? Convert.ToInt32(ConfigurationManager.AppSettings["RowsOnPage"]) : 10;
                int countPages = (CountRows.HasValue) ? (int)Math.Ceiling((double)CountRows / (double)onPage) : 0;
                return countPages;
            }
        }
        public string NumPageSessionName { get; set; }
        public int CurrentPageNumber
        {
            get
            {
                return (Session[NumPageSessionName] == null) ? 1 : Convert.ToInt32(Session[NumPageSessionName]);
            }
            set
            {
                Session[NumPageSessionName] = value;
            }
        }


        protected void Page_Load(object sender, EventArgs e)
        {
            Bind();
        }

        public void Bind()
        {
            if (CountRows != null)
            {
                this.PagingDataList.Visible = true;
                this.GotoPageButtonLast.Visible = true;
                this.GotoPageButtonFirst.Visible = true;

                if (CountPages > 1)
                {
                    List<int> pagesList = new List<int>();

                    int startNum = ((CurrentPageNumber <= CountVisible) || ((CountVisible * 2 + 1) >= CountPages))
                                    ? 1
                                    : (CurrentPageNumber >= CountPages - CountVisible)
                                        ? CountPages - CountVisible
                                        : CurrentPageNumber - CountVisible;
                    int endNum = startNum + CountVisible * 2;
                    if (endNum > CountPages)
                    {
                        if ((CountVisible * 2 + 1) < CountPages)
                            startNum = CountPages - CountVisible * 2;
                        endNum = CountPages;
                    }

                    for (int i = startNum; i <= endNum; i++)
                    {
                        pagesList.Add(i);
                    }

                    this.PagingDataList.DataSource = pagesList;
                    this.PagingDataList.DataBind();

                    this.GotoPageButtonFirst.CommandArgument = "1";
                    this.GotoPageButtonLast.CommandArgument = CountPages.ToString();
                    if ((CurrentPageNumber + CountVisible > CountPages) || (CountVisible * 2 + 1 >= CountPages))
                        this.GotoPageButtonLast.Visible = false;
                    if ((CurrentPageNumber - CountVisible <= 1) || (CountVisible * 2 + 1 >= CountPages))
                        this.GotoPageButtonFirst.Visible = false;

                    if (!IsPostBack)
                    {
                        CurrentPageNumber = 1;
                    }
                    FillListPaging();
                }
                else
                {
                    this.PagingDataList.Visible = false;
                }
            }
            else
            {
                this.PagingDataList.Visible = false;
            }
        }


        private void FillListPaging()
        {
            if (this.PagingDataList.Items != null)
            {
                foreach (DataListItem item in this.PagingDataList.Items)
                    item.BackColor = System.Drawing.Color.Transparent;

                if (this.PagingDataList.DataSource != null && this.PagingDataList.DataSource is List<int>)
                {
                    for (int i = 0; i < (this.PagingDataList.DataSource as List<int>).Count; i++)
                    {
                        if ((this.PagingDataList.DataSource as List<int>)[i] == CurrentPageNumber)
                        {
                            this.PagingDataList.Items[i].BackColor = ActivePageColor;
                            break;
                        }
                    }
                }
            }
        }


        /// <summary>
        /// Событие нажатия на LinkButton для перехода на другую страницу списка Расходных накладных`
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void GotoPageButton_Click(object sender, EventArgs e)
        {
            try
            {
                int pageNum = Convert.ToInt32((sender as LinkButton).CommandArgument);
                CurrentPageNumber = pageNum;

                Bind(); // Перерисовка Item'ов

                OnPageNumberChange(this, new PageNumberChangeEventArgs(pageNum)); // Инициируется событие смены номера страницы
            }
            catch (Exception ex)
            { }
        }


        #region Событие смены номера страницы в списке возможных номеров страниц

        // Delegate
        public delegate void PageNumberChangeHandler(object sender, PageNumberChangeEventArgs data);

        // The event
        public event PageNumberChangeHandler PageNumberChange;

        // The method which fires the Event
        protected void OnPageNumberChange(object sender, PageNumberChangeEventArgs data)
        {
            // Check if there are any Subscribers
            if (PageNumberChange != null)
            {
                // Call the Event
                PageNumberChange(this, data);
            }
        }

        #endregion Событие смены номера страницы в списке возможных номеров страниц

    }


    public class PageNumberChangeEventArgs : EventArgs
    {
        public object NewValue { get; internal set; }
        public PageNumberChangeEventArgs(object newValue)
        {
            this.NewValue = newValue;
        }
    }
    
}